package com.dtflys.easyel.transform;

import com.dtflys.easyel.ast.ASTConstant;
import com.dtflys.easyel.ast.ASTTimeDuration;
import com.dtflys.easyel.ast.ASTType;
import org.antlr.v4.runtime.Token;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class TimeDurationTransformer extends ExpressionTransformer {

    public ASTTimeDuration transform(Token timeToken) {
        String time = timeToken.getText();

        ASTTimeDuration timeDuration = new ASTTimeDuration();

        ASTConstant hoursExpr;
        ASTConstant minutesExpr;
        ASTConstant secondsExpr;
        ASTConstant millisecondsExpr;

        String[] timeArgs = time.split(":");
        String hh = timeArgs[0];
        String mm = timeArgs[1];
        Integer hours = Integer.parseInt(hh);
        Integer minutes = Integer.parseInt(mm);
        Integer seconds = null;
        Integer milliseconds = null;

        hoursExpr = new ASTConstant(hours, ASTType.INTEGER, null);
        minutesExpr = new ASTConstant(minutes, ASTType.INTEGER, null);
        setPosition(hoursExpr, timeToken.getLine(), timeToken.getLine(),
                timeToken.getStartIndex(), timeToken.getStartIndex() + 1);
        setPosition(minutesExpr, timeToken.getLine(), timeToken.getLine(),
                timeToken.getStartIndex() + 3, timeToken.getStartIndex() + 4);
        timeDuration.setHours(hoursExpr);
        timeDuration.setMinutes(minutesExpr);

        if (timeArgs.length > 2) {
            String ss = timeArgs[2];
            seconds = Integer.parseInt(ss);
            secondsExpr = new ASTConstant(seconds, ASTType.INTEGER, null);
            setPosition(secondsExpr, timeToken.getLine(), timeToken.getLine(),
                    timeToken.getStartIndex() + 6, timeToken.getStartIndex() + 7);
            timeDuration.setSeconds(secondsExpr);
        }

        if (timeArgs.length > 3) {
            String SS = timeArgs[3];
            milliseconds = Integer.parseInt(SS);
            millisecondsExpr = new ASTConstant(milliseconds, ASTType.INTEGER, null);
            setPosition(millisecondsExpr, timeToken.getLine(), timeToken.getLine(),
                    timeToken.getStartIndex() + 10, timeToken.getStartIndex() + 11);
            timeDuration.setMilliseconds(millisecondsExpr);
        }

        setPosition(timeDuration, timeToken);
        printNode(timeDuration);
        return timeDuration;
    }

}
